package control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import model.Conexoes;
import model.Processamento;
import view.Vista;

public class Controle extends Thread implements ActionListener,WindowListener{

	private ServerSocket welcomeSocket;
	private ArrayList<Processamento> processamento;
	private Processamento temp;
	private Socket connectionSocket;
	private Conexoes conexoes;
	private Vista vista;
	
	public Controle(){
		this.conexoes =new Conexoes();
		this.vista=new Vista();
		this.vista.getJMenuItem().addActionListener(this);
		this.vista.getJanela().addWindowListener(this);
	}
	
	public void run(){
		try{
			this.welcomeSocket=new ServerSocket(9999);
			this.processamento=new ArrayList<Processamento>(0);
			while(true){
				this.connectionSocket=welcomeSocket.accept();
				this.vista.escreveNaTela(" cliente "+this.connectionSocket.getInetAddress().toString().substring(1)+" conectou");
				this.temp=new Processamento(connectionSocket,conexoes,vista);
				this.temp.setName("conexao:"+temp.getId());
				this.processamento.add(temp);
				this.temp.start();
			}
		}catch(IOException ioe){}
	}
	
	public void windowClosing(WindowEvent e){
		System.exit(0);
	}
	
	public void actionPerformed(ActionEvent e){
		System.exit(0);
	}
	
	public void windowActivated(WindowEvent e){}
	public void windowDeactivated(WindowEvent e){}
	public void windowDeiconified(WindowEvent e){}
	public void windowClosed(WindowEvent e){}
	public void windowIconified(WindowEvent e){}
	public void windowOpened(WindowEvent e){}
	
	public static void main(String[] args) {
		Controle ss=new Controle();
		ss.setName("escuta");
		ss.start();
	}
}
